package com.gopay.scheduler.job;

import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.gopay.common.constants.trans.TxnStaCode;
import com.gopay.common.constants.txncd.IntTxnCd;
import com.gopay.common.cps.dao.gsrt.GsrtAccountDrawDao;
import com.gopay.common.cps.manager.gsrt.GsrtAccountDrawQueryManager;
import com.gopay.common.domain.gsrt.GsrtAccountDraw;
import com.gopay.remote.cps.notify.order.MerNotifyOrderRemoteService;
import com.gopay.scheduler.GopayBaseJob;


/**
 * 处理G商融通提现超时订单清理任务。
 * 
 * 在此任务中，主要进行以下工作：
 * 根据超时时间清理除G商融通提现订单中，订单状态为处理中并且订单的创建时间与当前时间的时间差大于等于timeSpan
 * ，订单交易状态设置为“失效” 
 * 
 * @author ZYT
 */
public class CheckTimeoutGsrtDrawJob extends GopayBaseJob {

	@Resource(name = "merOrderNotifyClient")
    private MerNotifyOrderRemoteService merOrderNotifyClient;
	
	@Resource(name = "gsrtAccountDrawQueryManager")
	private GsrtAccountDrawQueryManager gsrtAccountDrawQueryManager;
	
	@Resource(name = "gsrtAccountDrawDao")
	private GsrtAccountDrawDao gsrtAccountDrawDao;

	private Logger logger = LoggerFactory
			.getLogger(CheckTimeoutGsrtDrawJob.class);
	public void doJobInternal() {
		logger.info("G商融通更新提现订单定时任务开始执行");
		// 根据超时时间清理除超时订单
		// 超时时间（分钟）
		int timeSpan = 10;
		List<Object> otherMainOrederList = gsrtAccountDrawQueryManager.findTimeoutListByTimeSpan(timeSpan);
		if (!(otherMainOrederList.isEmpty())) {

			logger.info("已找到" + otherMainOrederList.size()
					+ "个超时订单, 现在开始清理这些订单");
			for (Object obj : otherMainOrederList) {

				String id = String.valueOf(obj);
				if(StringUtils.isNotBlank(id)){
					//List<GsrtCustBid> gsrtCustBidList = gsrtCustBidQueryManager.findByGopayOrderId(gopayOrderId);
					GsrtAccountDraw gsrtAccountDraw = gsrtAccountDrawDao.find(GsrtAccountDraw.class, Long.valueOf(id));
					if (gsrtAccountDraw != null) {
						gsrtAccountDraw.setTxnStaCd(TxnStaCode.TXN_STA_CD_20001.value);
						gsrtAccountDraw.setCommentRk("用户操作超时，页面失效");
						gsrtAccountDraw.setLastUpdTs(new Date());
						gsrtAccountDraw.setTranFinishTime(new Date());
						gsrtAccountDrawDao.update(gsrtAccountDraw);
						logger.info("G商融通清理超时提现业务订单：" + id + "订单成功");
						merOrderNotifyClient.addGsrtMerNotify(gsrtAccountDraw.getMerOrderId(), gsrtAccountDraw.getTransDtlSq(), IntTxnCd._00800.value, false);
		                logger.error("cron执行成功网关G商融通提现处理成功，异步通知商户。提现业务表id[" + id + "]");
					}
				}
			}
			logger.info("task - timeout the order has been done to clean up regularly");
		} else {
			
			logger.info("没有需要清理的超时请求");
		}

	}

}
